package com.container.registration;

import com.container.core.MyServletContext;

import javax.servlet.*;
import java.util.*;

public class MyServletRegistration extends AbstractNettyRegistration implements ServletRegistration.Dynamic {
    private Servlet servlet;
    private volatile boolean initialized;//用来实现懒加载
    private Collection<String> urlMappings = new LinkedList<>();

    public MyServletRegistration(MyServletContext context, String servletName, String className, Servlet servlet) {
        super(servletName, className, context);
        this.servlet = servlet;
    }

    //double-check获取servlet实例
    public Servlet getServlet() throws ServletException {
        if (!initialized) {
            synchronized(this) {
                if (!initialized) {
                    //初始化servlet实例
                    if (servlet == null) {
                        try {
                            servlet = (Servlet) Class.forName(getClassName()).newInstance();//反射获取实例
                        } catch (Exception e) {
                            throw new ServletException(e);
                        }
                    }
                    servlet.init(this);
                    initialized = true;
                }
            }
        }
        return servlet;
    }

    @Override
    public Set<String> addMapping(String... patterns) {
        MyServletContext context = getNettyContext();
        for (String p : patterns) {
            try {
                context.addMapping(p, getName(), getServlet());
            } catch (ServletException e) {
                
            }
        }
        urlMappings.addAll(Arrays.asList(patterns));
        return new HashSet<>(urlMappings);
    }

    @Override
    public Collection<String> getMappings() {
        return urlMappings;
    }

    @Override
    public void setLoadOnStartup(int loadOnStartup) {}

    @Override
    public Set<String> setServletSecurity(ServletSecurityElement constraint) {
        return null;
    }

    @Override
    public void setMultipartConfig(MultipartConfigElement multipartConfig) {}

    @Override
    public void setRunAsRole(String roleName) {}

    @Override
    public String getRunAsRole() {
        return null;
    }

}
